//
//  YFComposeViewController.swift
//  仿新浪微博
//
//  Created by 杨帆 on 16/7/11.
//  Copyright © 2016年 杨帆. All rights reserved.
//

import UIKit
import SVProgressHUD

// 撰写微博控制器
class YFComposeViewController: UIViewController {
    
    // 文本编辑视图
    @IBOutlet weak var textView: UITextView!
    
    // 底部工具栏
    @IBOutlet weak var toolbar: UIToolbar!

    // 发布按钮
    @IBOutlet var sendButton: UIButton!
    
    // 标题标签
    @IBOutlet var titleLabel: UILabel!
    
    // 工具栏底部约束
    @IBOutlet weak var toolbarBottomCons: NSLayoutConstraint!
    
    // 视图生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        // 监听键盘通知 - UIWindow.h
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardChanged),
                                               name: NSNotification.Name.UIKeyboardDidChangeFrame,
                                               object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 激活键盘
        textView.becomeFirstResponder()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
        // 关闭键盘
        textView.resignFirstResponder()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        // 设置文本视图的代理
        textView.delegate = self
    }
    
    // MARK: - 键盘监听方法
    @objc private func keyboardChanged(n: Notification) {
    
        // 1. 目标rect
        guard let rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue(),
            duration = (n.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
            else {
                return
        }
        
        // 2. 设置底部约束的高度
        let offset = view.bounds.height - rect.origin.y
        
        // 3. 更新底部约束
        toolbarBottomCons.constant = offset
        
        // 4. 动画更新约束
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }

    }

    @objc private func close() {
    
        dismiss(animated: true, completion: nil)
    }
    
    // MARK: - 按钮监听方法
    // 发布微博
    @IBAction func postStatus() {
        
        // 1. 获取微博文字
        guard let text = textView.text else {
            return
        }
        
        // 2. 发布微博
        YFNetWorkManager.shared.postStatus(text: text) { (result, isSuccess) in
//            print(result)
            
            // 修改指示器样式
            SVProgressHUD.setDefaultStyle(.dark)
            
            let message = isSuccess ? "发布成功" : "发送失败"
            
            SVProgressHUD.showInfo(withStatus: message)
            
            // 如果成功 延迟一段时间关闭当前窗口
            if isSuccess {
            
                DispatchQueue.main.after(when: DispatchTime.now() + 1) {
                
                    // 恢复样式
                    SVProgressHUD.setDefaultStyle(.light)
                    
                    self.close()
                }
            }
            
        }
    }

}

// MARK: - UITextViewDelegate
extension YFComposeViewController: UITextViewDelegate {

    // 文本视图文字变化
    func textViewDidChange(_ textView: UITextView) {
        sendButton.isEnabled = textView.hasText()
    }
}

private extension YFComposeViewController {
    
    func setupUI() {
    
        view.backgroundColor = UIColor.white()
        
        setupNavigationBar()
    
        setupToolbar()
    }
    
    // 设置工具栏
    func setupToolbar() {
        
        let itemSettings = [["imageName": "compose_toolbar_picture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background"],
                            ["imageName": "compose_add_background"]]

        // 遍历数组
        var items = [UIBarButtonItem]()
        for s in itemSettings {
        
            guard let imageName = s["imageName"] else {
                
                continue
            }
            
            let image = UIImage(named: imageName)
            let imageHL = UIImage(named: imageName + "_highlighted")
            
            let btn = UIButton()
            
            btn.setImage(image, for: [])
            btn.setImage(imageHL, for: .highlighted)
            
            btn.sizeToFit()
            
            // 追加按钮
            items.append(UIBarButtonItem(customView: btn))
            
            // 追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        
        // 删除末尾弹簧
        items.removeLast()
        
        toolbar.items = items
    
        
    }
    
    // 设置导航栏
    func setupNavigationBar() {
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(close))
        
        // 设置发送按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        
        // 设置标题视图
        navigationItem.titleView = titleLabel
        
        sendButton.isEnabled = false
    }



}
